#include "timer.h"
#include "stm32f1xx_hal.h"

static int update_times=0;
static int capture_state=0;
static int capture_value_up=0;
static int capture_value_down=0;
static int capture_value=0;

void TIM4_IRQHandler(void)
{
	uint16_t tsr;
	tsr=TIM4->SR;

	if(tsr&0001) // update ie
	{	    
		if(capture_state) {
			update_times++;	 
		}
	}
	
	if(tsr&(1<<4)) //capture ie
	{	
		if(TIM4->CCER & (1<<13)) //jump low		
		{	  						
			capture_value_down = TIM4->CCR4;
			TIM4->CCER &= ~(1<<13); //change to jump_high
			
			if( update_times==0 ) {
				capture_value = capture_value_down - capture_value_up;
			} else {
				capture_value = ((update_times * 20000) + capture_value_down) - capture_value_up;
			}	
			
			update_times = 0;
			capture_state = 0;
		}
		else  							
		{			
			capture_state = 1;
			capture_value_up = TIM4->CCR4;
			TIM4->CCER |= 1<<13; //change to jump_low
		}		    
	}			     	    					   

	TIM4->SR=0;//clean ie flag
}


void timer_init(void)
{
	__HAL_RCC_GPIOB_CLK_ENABLE();
	__HAL_RCC_AFIO_CLK_ENABLE();
	__HAL_RCC_TIM4_CLK_ENABLE();	
	
	GPIOB->CRH &= 0xFFFFFF00;
	GPIOB->CRH |= 0x0000004B;
	
	TIM4->PSC = 71;
	TIM4->ARR = 20000;
	
	TIM4->CCMR2  = 0;
	TIM4->CCMR2 |= 0x60;//CH3 PWM1
	TIM4->CCMR2 |= 0x01<<8;//CH4 CAP
	
	TIM4->CCER  |= 0x01<<8;//enable ch3
	TIM4->CCER  |= 0x01<<12;//enable ch4
	
	TIM4->DIER |= 1<<4; //CH4 IE
	TIM4->DIER |= 1;//UPDATE IE
	
	TIM4->CCR3 = 1500;
	TIM4->CR1 |= 0x01;
	
	HAL_NVIC_SetPriority(TIM4_IRQn,1,1);
	HAL_NVIC_EnableIRQ(TIM4_IRQn);
}

void pwm_output(int us)
{
	if(us<1100)
	{
		us =1100;
	}
	if(us > 1900)
	{
		us = 1900;
	}
	TIM4->CCR3 = (uint16_t)us;
}

int get_capture(void)
{
	return capture_value;
}
